package com.example.redistemplate;

import com.example.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Map;

@SpringBootTest
class StringRedisTemplateTest2 {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    void testString() {
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        value.set("name","露西");
        Object o = value.get("name");
        System.out.println(o);
    }

    @Test
    void testUser() throws JsonProcessingException {
        User user = new User("李四", 142);
        //手动序列化
        String json = mapper.writeValueAsString(user);

        //写入数据
        stringRedisTemplate.opsForValue().set("user:100",json);

        //获取数据
        String s = stringRedisTemplate.opsForValue().get("user:100");
        System.out.println(s);

        //手动反序列化
        User user1 = mapper.readValue(s, User.class);
        System.out.println(user1);

        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        value.set("user:200",json);

        String s1 = value.get("user:200");
        System.out.println(s1);
        User user2 = mapper.readValue(s1, User.class);
        System.out.println(user2);
    }

    @Test
    void testHash() {

        HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();

        hash.put("user:300","name","学校");
        hash.put("user:300","age","21");

        Map<Object, Object> entries = hash.entries("user:300");
        System.out.println(entries);
    }

}
